#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os
import json
sys.path.append("./src")
import sqliteWrite
import cherrypy		#sudo aptitude install python-cherrypy3
import html
import encrypt

psqlMgr = sqliteWrite.sqliteWrite('db/restaurant.db')
#hostPort = 8080
hostPort = 30823





class wedding(object):
	def index(self):
		return html.read_basic_html('html/index.html', {})

	def info(self):
		return html.read_basic_html('html/about.html', {})

	def pictures(self):
		return html.read_basic_html('html/pictures.html', {})

	def registry(self):
		return html.read_basic_html('html/registry.html', {})

	def get_picture_list(self):
		img_files = os.listdir('./wedding_pics') 
		
		good_ones = []
		for i in img_files:
			name = './wedding_pics/' + i
			if os.path.isfile(name):
				good_ones.append('/wedding_pics/' + i)

		print good_ones
		return json.dumps(good_ones, sort_keys=True, indent=4)


	def save_image(self, myFile):
		if myFile.file == None:
			return 'You must choose a file first before pressing the submit button.'
	
		AcceptFormats = ['image/x-citrix-png', 'image/x-citrix-jpeg','image/png','image/jpeg', 'image/gif', 'image/bmp','image/pjpeg','image/x-png']
	
		size = 0
		total = ''
		while True:
			data = myFile.file.read(8192)
			if not data:
				break
			size += len(data)
			if size > 400000:
				return 'error : This file is not uploaded because it is larger than 400kb. Please pick a smaller file'
			total += data
	
	
		fileTypeF = str(myFile.content_type).lower()
		if fileTypeF not in AcceptFormats:
			return 'error : ' + fileTypeF + ' is the wrong file type, we only accept bmp, gif, png, jpg, and jpeg images.'
	
		
		newFname = encrypt.getRandomStr(12, '', os.path.splitext(myFile.filename)[1])
	
		write_file_name = './wedding_pics/' + newFname
		fin = open(write_file_name, 'w')
		fin.write(total)
		fin.close()
		
		return '1'




#	new function here
	get_picture_list.exposed = True
	save_image.exposed = True

	index.exposed = True
	info.exposed = True
	pictures.exposed = True
	registry.exposed = True



if __name__ == '__main__':
	current_dir = os.path.dirname(os.path.abspath(__file__))
				 
	
	conf = 	{
				'/': {'tools.encode.on':True, 'tools.encode.encoding':'utf-8', 'tools.proxy.on':True},
				'/': {'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, '')},
				'/html': {'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, 'html'), 'tools.staticdir.content_types': {'css': 'text/css', 'manifest': 'text/cache-manifest'}},
				'/img': {'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, 'img')},
				'/css': {'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, 'css')},
				 'global':	{ 'server.environment': 'production',
				'engine.autoreload_on': True,
				'engine.autoreload_frequency': 5,
				'server.socket_host': '0.0.0.0',
				'server.socket_port': hostPort}
			}
	
	cherrypy.quickstart(wedding(), '/', config=conf)

	



